import React from 'react';
import { observer, inject } from 'mobx-react';
import * as mobx from 'mobx';
import { getAntd,getEcCom,getLabel } from '../../util/convert';
import * as _ from '../../util/public/common';
import base from '../../util/base';

@inject('statusStore')
@observer
export default class Status extends React.Component {
    constructor(props) {
		super(props);
    }
    componentDidMount(){
        const { statusStore,location } = this.props;
        const queryParams = location && location.query || {};
        const requestid = _.isEmpty(queryParams) ? this.props.requestid : queryParams.requestid;
        statusStore.setBaseParam({requestid});
        statusStore.switchCard('all');
        statusStore.loadCounts();
    }
    render() {
        const { Row,Col,Card,Table } = getAntd();
        const { WeaSelect,WeaBrowser,WeaFormItem,WeaSearchGroup } = getEcCom();
        const { statusStore } = this.props;
        const { cardid,counts,dataMap,hideRowKeys,nodeOptions,setSelectedNode,setSelectedOperator,selectedNode,selectedOperator,controlHideAllRow,isHideAll } = statusStore;
        const cardData = dataMap.get(cardid) || {};
        const hasAdSearch = selectedOperator || selectedNode != "-1";//是否有高级搜索
        const {loading = false} = base.globalStore;
        const cardInfo = [
			{id:'all', title:getLabel(15945,'总人次'), color:'#3ac8d2', num:counts.allcount, icon:'icon-workflow-form-Total-person-time'},
			{id:'submit', title:getLabel(15176,'已提交'), color:'#8dc139', num:counts.submitcount, icon:'icon-workflow-form-Has-been-submitted'},
			{id:'nosubmit', title:getLabel(15178,'未提交'), color:'#b37bf8', num:counts.nosubmitcount, icon:'icon-workflow-form-Not-submitted'},
			{id:'view', title:getLabel(18006,'已查看'), color:'#009bff', num:counts.viewcount, icon:'icon-workflow-form-Already-view'},
			{id:'noview', title:getLabel(18007,'未查看'),  color:'#ff1924', num:counts.noviewcount, icon:'icon-workflow-form-Not-viewed'}
		];
        const statusCode = [
            '',
            <span style={{color:"#ff1924"}}>{getLabel(18007,'未查看')}</span>,
            <span style={{color:"#009bff"}}>{getLabel(18006,'已查看')}</span>,
            <span style={{color:"#666666"}}>{getLabel(15176,'已提交')}</span>,
            getLabel(20387,'暂停'),getLabel(16210,'撤销'),getLabel(26472,'启用'),
            <span style={{color:"#666666"}}>{getLabel(505288,'已查阅')}</span>
        ];
        const tableColumn = (cardid === 'all' && !hasAdSearch) ? [
			{title:getLabel(15486,'序号'), dataIndex:'num', key:'num', width:'8%'},
			{title:getLabel(33417,'节点'), dataIndex:'operator', key:'operator', width:'16%'},
			{title:getLabel(84645,'操作情况统计'), dataIndex:'status', key:'status', width:'16%', colSpan:4},
            {title:'', dataIndex:'receivedate', key:'receivedate', width:'20%', colSpan:0},
			{title:'', dataIndex:'operatedate', key:'operatedate', width:'20%', colSpan:0},
            {title:'', dataIndex:'intervel', key:'intervel', colSpan:0}
		]: [
			{title:getLabel(17482,'操作人'), dataIndex:'operator', key:'operator', width:'12%'},
			{title:getLabel(33417,'节点'), dataIndex:'nodename', key:'nodename', width:'16%'},
			{title:getLabel(27094,'操作状态'), dataIndex:'status', key:'status', width:'16%'},
			{title:getLabel(18002,'接收时间'), dataIndex:'receivedate', key:'receivedate', width:'18%'},
			{title:getLabel(15502,'操作时间'), dataIndex:'operatedate', key:'operatedate', width:'18%'},
			{title:getLabel(386337,'操作耗时'), dataIndex:'intervel', key:'intervel'},
		];
        let tableData = [];
        let expandedRowKeys = [];
        let dataLength = 0;
        const totalLength = parseInt(counts[`${cardid}count`] || 0);
        if(cardid === 'all' && !hasAdSearch){//为全部且没有搜索
            const nodeSize = _.size(cardData);
            for(let i=0; i<nodeSize; i++){
                const node = cardData[`key${i}`];
                if(!node)
                    continue;
                let rowDetail = [];
                node.list.map((r,j) =>{
                    rowDetail.push({
                        num: '',
                        key: `rowDetail_${i+1}_${j+1}`,
                        operator: this.getOperatorObj(r),
                        status: this.getStatusName(r,statusCode),
                        receivedate: r.receivedate,
                        operatedate: r.operatedate,
                        intervel: r.intervel
                    });
                });
                dataLength += rowDetail.length;
                let nodeRowData = {
                    num: i+1,
                    key: `rowDataHead_${i+1}`,
                    operator: node.nodename,
                    status: `${getLabel(84646,'操作者总计')}: ${node.listcount}`,
                    receivedate: <span style={node.submitCount == 0 ? {} : {color:'#666666'}}>{`${getLabel(15176,'已提交')}: ${node.submitCount}`}</span>,
                    operatedate: <span style={node.viewCount == 0 ? {} : {color:'#009bff'}}>{`${getLabel(18006,'已查看')}: ${node.viewCount}`}</span>,
                    intervel: <span style={node.noviewCount == 0 ? {} : {color:'#ff1924'}}>{`${getLabel(18007,'未查看')}: ${node.noviewCount}`}</span>,
                    children:[{
                        num: '',
                        key: `rowDetailHead_${i+1}`,
                        operator: getLabel(17482,'操作人'),
                        status: getLabel(27094,'操作状态'),
                        receivedate: getLabel(18002,'接收时间'),
                        operatedate: getLabel(15502,'操作时间'),
                        intervel: getLabel(18003,'操作耗时'),
                        children: rowDetail
                    }]
                };
                if(_.indexOf(hideRowKeys, `rowDataHead_${i+1}`) == -1)
                    expandedRowKeys.push(`rowDataHead_${i+1}`);
                expandedRowKeys.push(`rowDetailHead_${i+1}`);
                tableData.push(nodeRowData);
            }
        }else{
            // !_.isEmpty(cardData) && _.forIn(cardData, (node,k) =>{
            //         console.log("key", k);
            //         node.list.map(r =>{
            //             tableData.push({
            //                 operator: this.getOperatorObj(r),
            //                 nodename: node.nodename,
            //                 status: statusCode[r.statuscode],
            //                 receivedate: r.receivedate,
            //                 operatedate: r.operatedate,
            //                 intervel: r.intervel
            //             });
            //         })
            // });
            const nodeSize = _.size(cardData);
            if(!_.isEmpty(cardData)) {
                for(let i=0; i<nodeSize; i++) {
                    const node = cardData[`key${i}`];
                    if(!node)
                        continue;
                    node.list.map(r =>{
                        tableData.push({
                            operator: this.getOperatorObj(r),
                            nodename: node.nodename,
                            status: this.getStatusName(r,statusCode),
                            receivedate: r.receivedate,
                            operatedate: r.operatedate,
                            intervel: r.intervel
                        });
                    })
                }
            }
            dataLength = tableData.length;
        }
        return (
            <div className="wf-status">
	            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@3raf26`}>
	            	<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@9lw00m`} className="wf-status-card-wapper" span={24} style={{padding:'0 0 20px 0'}}>
	            		{
	            			cardInfo.map((t,i) =>{
								let cardStyle = (t.id === cardid || (hasAdSearch && cardid.indexOf('_') > -1 && t.id === cardid.substring(0, cardid.indexOf('_')))) ? {boxShadow:'0 0 5px #008aff', border:'1px solid #008aff'} : {border:'1px solid #d5d5d5'};
								cardStyle["color"] = t.color;
                                cardStyle["marginRight"] = i < 3 ? "1.25%" : "0px";
								cardStyle["float"] = i == 4 ? "right" : "left";
                                return (
                                    <div className="wf-status-card" style={cardStyle} title={t.title} onClick={this.switchCard.bind(this,t.id)}>
                                        <i className={t.icon} />
                                        <div>
                                            <p style={{fontSize:"26px"}}>{t.num}</p>
                                            <p style={{fontSize:"12px", color:'#5b5b5b'}}>{t.title}</p>
                                        </div>
	            				    </div>
                                )
	            			})
                        }
	            	</Col>
	            </Row>
	            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@wms4d3`} className="wf-status-content">
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@jy04po`} span={24} style={{border:'1px solid #e9e9e9', borderBottom:"none"}}>
                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@pqiyc6`} className="adSearchGroup" needTigger={true} showGroup={true} items={[
                        {com: (
                            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@psmfi6@nodefilter`}
                                label={getLabel(84657, "按节点过滤")}
                                labelCol={{span: 9}}
                                wrapperCol={{span: 12}}
                            >
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@zmpbyo@nodefilter`}
                                    options={mobx.toJS(nodeOptions)}
                                    onChange={(key,name) => {
                                        setSelectedNode(key);
                                        statusStore.switchCard(cardid);
                                    }}
                                    value={selectedNode}
                                />
                            </WeaFormItem>
                        )
                    },
                    {com: (
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@gw8etz@operfilter`}
                            label={getLabel(84658, "按操作者过滤")}
                            labelCol={{span: 9}}
                            wrapperCol={{span: 12}}
                        >
                            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@srsyes@operfilter`} type="1" ref="operatorBrowser" title={getLabel(18214,"请选择")} onChange={(id,name,data) => {
                                setSelectedOperator(id);
                                statusStore.switchCard(cardid);
                            }}></WeaBrowser>
                        </WeaFormItem>
                    )
                    }]}>    
                    </WeaSearchGroup>
                    </Col>
                    {
                        (cardid === 'all' && !hasAdSearch) ?
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@lo5vet`} span={24} style={{border:'1px solid #e9e9e9', borderBottom:dataLength<totalLength ? "none" : "1px solid #e9e9e9", position: "relative"}}>
                                <span title={isHideAll ? getLabel(84533, "展开全部") : getLabel(84532, "收缩全部")} className="icon-coms-release cursor-pointer" onClick={() => {controlHideAllRow(_.size(cardData))}}></span>
                                <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@9r3hbh`} pagination={false} columns={tableColumn} dataSource={tableData} size="middle"
                                    className="wf-status-table-main" expandedRowKeys={expandedRowKeys} onRowClick={this.setHideRowKeys} />
                            </Col> :
                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@eu6ks8`} span={24}>
                                <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@wemji2`} pagination={false} columns={tableColumn} dataSource={tableData} size="middle"
                                    className="wf-status-table-single" />
                            </Col>
	            	}
                    {
                        !loading && dataLength < totalLength && <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@q7stc1`} span={24}>
                            <div style={{textAlign:"center"}}>
                                <span className="wf-status-loadmore" onClick={this.loadMoreData}>
                                    <i className="anticon anticon-arrow-down" style={{marginRight:"4px"}}></i>
                                    <span>{getLabel(82720,'加载更多')}</span>
                                </span>
                            </div>
                        </Col>
                    }
	            </Row>
            </div>
        )
    }

    getStatusName(itemInfo = {},statusNameInfo = {}){
        const {statuscode} = itemInfo;
        return statusNameInfo[statuscode];
    }

    getOperatorObj(info){
        let obj = new Array();
        if(!!info.beagentid){    //存在代理
            obj.push(<a className="wea-hrm-card" href={`javaScript:openhrm(${info.beagentid})`} onClick={event => window.pointerXY(event)}>{info.beagentname}</a>);
            obj.push(<span className="wf-status-connect-symbol">-></span>);
        }
        if(info.operatortype == "0"){
            obj.push(<a className="wea-hrm-card" href={`javaScript:openhrm(${info.operatorid})`} onClick={event => window.pointerXY(event)}>{info.operator}</a>);
        }else{
            obj.push(<a target="_blank" className="wea-hrm-card" href={`/spa/crm/static/index.html#/main/crm/customerView?customerId=${info.operatorid}`} >{info.operator}</a>);
        }
        return <span>{obj}</span>;
    }
    switchCard(cardid){
        const { statusStore } = this.props;
        statusStore.clearnSearchStatus();//清理查询状态
        this.refs.operatorBrowser && this.refs.operatorBrowser.set([]);
        statusStore.switchCard(cardid);
    }
    loadMoreData = (par) => {
        const { statusStore } = this.props;
        statusStore.loadData(false);
    }
    setHideRowKeys = (r) => {
		if(r.key.indexOf('rowDataHead_') === 0){
            const { statusStore } = this.props;
            statusStore.controlHideRow(r.key);
		}
    }
}
